package com.key.puzzlemodel.mvvm

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

abstract class BaseMVVMFragment<VDB: ViewDataBinding, VM: ViewModel> : Fragment() {

    lateinit var mVDB : VDB // 视图数据绑定
    lateinit var mVM : VM // ViewModel

    abstract val layoutId : Int // xml布局文件，子类指定


    /**
     * UI初始化，[子类必须实现]
     * 会在onCreate方法中获取DataBinding和ViewModel之后被调用
     */
    protected abstract fun initView(savedInstanceState: Bundle?)

    /**
     * 绑定监听事件
     */
    open fun bindEvent(){}



    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mVDB = DataBindingUtil.inflate(inflater, layoutId, container, false)
        return mVDB.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mVM = providerViewModel()
        mVDB.lifecycleOwner = this
        initView(savedInstanceState)
        bindEvent()
    }

    /**
     * 获取ViewModel
     */
    private fun providerViewModel() : VM {
        val genericSuperclass : ParameterizedType = javaClass.genericSuperclass as ParameterizedType
        val actualTypeArguments : Array<Type> = genericSuperclass.actualTypeArguments
        val vmClass : Class<VM> = actualTypeArguments[1] as Class<VM>
        return ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory(requireActivity().application)).get(vmClass)
    }
}